<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed} from 'vue'
import waybillTray from '@/api/abroad/waybillTray'
import { Message, Modal } from '@arco-design/web-vue'
import dicthelpApi from "@/api/dicthelpApi.js";
import {DictData} from "@/utils/crud/dictNew.js";
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";

const columnsDist = inject('columnsDist')
const span=ref(8)
const crudRef = ref()

const formRef=ref(null)
const currentStatus =ref('1')
// 表单数据
const rules = {
      type: [{ required: true, message:'',validateTrigger: 'blur'}, ],
  }
const formData = ref({
  parent_id:'',
  trays:[],
})
 //托盘列表
 const waybillTrayList = () => {
      waybillTray.getList({parent_id:formData.value.parent_id}).then(res => {  
        formData.value.trays=res.data.items
        formData.value.trays.forEach(function(item) {
          if(item.tray_count_actual==0){
            item.disabled=true
            item.tray_count_actual=item.shipment_list_sum_tray_count_estimate
          }
          if(item.parcel_count_actual==0){
            item.parcel_count_actual=item.shipment_list_sum_parcel_count_estimate
          }
          item.shipment_list.forEach(function(itemInfo) {
            if(itemInfo.parcel_count_actual===null){
              itemInfo.parcel_count_actual=itemInfo.parcel_count_estimate
            }
          })
          if(item.unpacking_at==null){
            item.unpacking_at=getCurrentDate()
          }
          
        }) 
        waybillServiceShipmentTypeListData()
      })      
    }
    const getCurrentDate = ()=> {
    const now = new Date();

    const year = now.getFullYear();

    // 注意：JavaScript的月份是从0开始的，所以需要加1
    const month = String(now.getMonth() + 1).padStart(2, '0');

    // 注意：JavaScript的日期也是从1开始的，所以不需要额外处理
    const date = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
}
const visible = ref(false)
 const waybillServiceShipmentTypeList=ref([])
//服务类型
const waybillServiceShipmentTypeListData = () => {
    dicthelpApi.waybillServiceShipmentTypeList({service:''}).then(res => {  
      waybillServiceShipmentTypeList.value=res.data
    })      
  }



// //table 选择
// //行数选中
const selected=ref([])
//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
const columns = ref([
  // {title: '拦截', dataIndex: 'is_intercept',slotName: 'is_intercept',type:'slider',required:true,align:'center',},
  {title: '服务类型', dataIndex: 'service_type_id',slotName: 'service_type_id',titleSlotName: 'customAgeTitle',type:'select',required:true,align:'center',},
  {title: '目的地', dataIndex: 'address_desc',slotName: 'address_desc',titleSlotName: 'customAgeTitle',required:true,align:'center', },
  // {title: '箱唛', dataIndex: 'shipment_no',slotName: 'shipment_no',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  // {title: 'CTNS', dataIndex: 'parcel_count_estimate',slotName: 'parcel_count_estimate',titleSlotName: 'customAgeTitle',type:'input',required:true,align:'center',},
  {title: 'Weight', dataIndex: 'shipment_list_sum_weight',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  {title: 'CBM', dataIndex: 'shipment_list_sum_volume',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  {title: '托盘(预计)', dataIndex: 'shipment_list_sum_tray_count_estimate',titleSlotName: 'customAgeTitle',type:'input',required:true,align:'center',},
  {title: '托盘(实际)', dataIndex: 'tray_count_actual',slotName: 'tray_count_actual',type:'input',align:'center',titleSlotName: 'customAgeTitle',required:true,},
  {title: '箱数(预计)', dataIndex: 'shipment_list_sum_parcel_count_estimate',type:'input',titleSlotName: 'customAgeTitle',required:true,align:'center',},
  {title: '箱数(实际)', dataIndex: 'parcel_count_actual',slotName: 'parcel_count_actual',type:'input',required:true,titleSlotName: 'customAgeTitle',align:'center',},
  {title: '入仓时间', dataIndex: 'unpacking_at',slotName: 'unpacking_at',type:'input', titleSlotName: 'customAgeTitle',align:'center',},
  {title: '备注', dataIndex: 'remark',slotName: 'remark',type:'input',align:'center',},
  {title: '操作', slotName: 'fixed',fixed: 'right',width: 107,align:'center'},
])
const expandable = {
      title: '运单展开',
      width: 80,
    };
  
    const expandableKey=ref([]) //默认展开
    //展开按钮改变
    const expandTap=(e)=>{
      if(expandableKey.value.includes(e)){
        expandableKey.value=[]
      }else{
        expandableKey.value=[]
        expandableKey.value.push(e)
      }
    }
    //实际箱数改变
    const parcelChang=(item)=>{
      expandableKey.value=[]
      expandableKey.value.push(item.id)

    }
  const onShow = async (value) => {
    console.log('value',value)
    visible.value = true
    if(value){
      formData.value.parent_id=value.id
      console.log('value',value)
      waybillTrayList()
    }
    
  }
  const buttonGroups = [
{
    title: '下载标签',
    api:waybillTray.printTap,
    auth: ['sea:waybillTray:print'],
    isDownload: true,
    hideStatus: [null],
  }
]

const emits = defineEmits(['addClick','emitClick'])
  //新增 //编辑
  const handleBeforeOk =async (formEl) => {
    // return false
      let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
    console.log(formParse)
      for(let i = 0 ; i <  formParse.trays.length; i++){
      if(!formParse.trays[i].tray_count_actual){
            Message.error('托盘(实际)必填')
            return;
      }
      if(!formParse.trays[i].parcel_count_actual){
            Message.error('箱数(实际)必填')
            return;
      }
    }
    if (!formEl) return
      await formEl.validate((valid) => {
        if (!valid) {
          waybillTray.recived(formParse).then(res => {
              Message.success(res.message || `接收托盘成功！`)
              emits('addClick');
              close()
            })
          
        }
      }) 
      
    };
    //单个保存
    const handleBeforeOkDg =async (item) => {
      let formParse = JSON.parse(JSON.stringify(formData.value)); // 深拷贝数据
    console.log(formParse)
    formParse.trays=[]
    formParse.trays.push(item)
    if(!item.tray_count_actual){
            Message.error('托盘(实际)必填')
            return;
      }
      if(!item.parcel_count_actual){
            Message.error('箱数(实际)必填')
            return;
      }
      waybillTray.recived(formParse).then(res => {
            Message.success(res.message || `接收托盘成功！`)
            waybillTrayList()
          }) 
      
    };
    
    const close = () => {
      formRef.value.resetFields();
      visible.value = false
      formData.value.trays=[]
      selected.value=[]
      formData.value.parent_id=''
   
    }
const onBeforeCancel=()=>{
  Modal.confirm({
        title: '确认关闭?',
        onOk: () => {
          close()
        },
      });
}
defineExpose({ onShow })
</script>

<template>
  <a-drawer v-model:visible="visible" v-if="visible" width="80%" :onBeforeCancel="onBeforeCancel">
        <template #title>
          <div >接收托盘</div>
          </template>
          <div style="display: flex;">
        <button-group :button-groups="buttonGroups" :dataList="formData.trays" :crud-ref="crudRef" :selected="selected"
                      :currentStatus="currentStatus"/>
      </div>
          <a-form ref="formRef" :rules="rules" :model="formData" style="margin-top: 10px;">
            <!-- columnsList -->
              <!-- <icon-plus-circle :size="26" @click="tabelAdd" style="cursor: pointer;" /> -->
              <a-table v-if="formData.trays!=''" ref="tableRef" row-key="id" :columns="columns" :data="formData.trays" :expandable="expandable" @expand="expandTap" :expanded-keys="expandableKey" v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" :bordered="false"  size="mini" column-resizable :pagination="false">
                <template #expand-row="{column,record}">
                  <div v-for="item in record.shipment_list" :key="item.id">
                    <div style="display: flex;margin-top: 10px;">
                      <div class="expandableList">
                        <span>运单号：{{ item.shipment_no}}</span>
                      </div>
                      <div class="expandableList">
                        <span>柜号：{{ item.container_no}}</span>
                      </div>
                      <div class="expandableList">
                        <span>预估箱数：{{ item.parcel_count_estimate}}</span>
                      </div>
                      <div class="expandableList">
                        <span>实际箱数：</span>
                        <a-input-number style="width: 70%;" v-model="item.parcel_count_actual" :min="0" placeholder="请输入" />
                      </div>
                    </div>
                  </div>
                </template>
                <template #customAgeTitle="{column}">
                  <div>
                    <span style="color:red;">*</span>{{column.title}}
                  </div>
                </template>
                <template #is_intercept="{ record }">
                  <a-switch :checked-value="1" :unchecked-value="0" v-model="record.is_intercept">
                  <template #checked>
                    是
                  </template>
                  <template #unchecked>
                    否
                  </template>
                </a-switch>
                  </template>
               
                  <template #service_type_id="{ record,rowIndex }" v-if="waybillServiceShipmentTypeList!=''">
                    <div>

                      {{ DictData(waybillServiceShipmentTypeList,'1',record.service_type_id)}}
                    </div>
                  </template>
                  <template #address_desc="{ record }">{{record?.address_desc}}</template>

                  <template #shipment_sum_weight="{ record }">
                    <a-input v-model="record.shipment_sum_weight" disabled placeholder="请输入" />
                  </template>
                  <template #shipment_sum_volume="{ record }">
                    <a-input v-model="record.shipment_sum_volume" disabled placeholder="请输入" />
                  </template>
                  <template #shipment_sum_tray_count_estimate="{ record }">
                    <a-input v-model="record.shipment_sum_tray_count_estimate" disabled placeholder="请输入" />
                  </template>
                  <template #tray_count_actual="{ record }">
                    <a-input-number v-model="record.tray_count_actual" :min="0.5" placeholder="请输入"/>
                  </template>
                  <template #shipment_sum_parcel_count_estimate="{ record }">
                    <a-input v-model="record.shipment_sum_parcel_count_estimate" disabled placeholder="请输入" />
                  </template>
                  <template #parcel_count_actual="{ record }">
                    <a-input-number v-model="record.parcel_count_actual" @change="parcelChang(record)" :min="1" placeholder="请输入" />
                  </template>
                  <template #unpacking_at="{ record }">
                    <a-date-picker
                      show-time
                      style="width: 100%;"
                      placeholder="请选择入仓时间"
                      v-model="record.unpacking_at"
                    />
                  </template>
                  <template #remark="{ record }">
                    <a-input v-model="record.remark" placeholder="请输入" />
                  </template>
                  <template #fixed="{ record,rowIndex  }">
                    <a-link  title="保存" @click="handleBeforeOkDg(record)"><icon-save /></a-link>
                  </template>
           </a-table>
        </a-form>
        <template #footer> 
          <div style="display: flex; justify-content: space-between;align-items: center;">
            <div style="color: rgb(50 193 148);">
              <!-- tips：先选择"服务项目"后在操作明细,请按要求填写(导入)单据信息 -->
            </div>
            <div>
              <a-button @click="visible = false" style="margin-right: 20px;">关闭</a-button>
              <a-button type="primary" @click="handleBeforeOk(formRef)">
                保存
              </a-button>
            </div>
          </div>       
        </template>
      </a-drawer>

</template>
<style>
   .form-top-main{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    width: 100%;
   }
   .tab-main{
    display: flex;
    align-items: center;
    margin: 10px 0;
   }
   .tab-main .arco-form-item{
    margin-bottom: 0;
   }
   .tab-main .arco-switch{
    margin-right: 20px;
   }
   .expandableList{
    display: flex;
    margin-right: 20px;
    width: 200px;
    align-items: center;
   }
</style>